home account info subscribe login search FAQ/help site map contact us


 
Brief Full
 Advanced
      Search
 Search Tips
To access the contents, click the chapter and section titles.

Bug Proofing Visual Basic: A Guide to Error Handling and Prevention
(Publisher: John Wiley & Sons, Inc.)
Author(s): Rod Stephens
ISBN: 0471323519
Publication Date: 11/01/98

Search this book:
 
Previous Table of Contents Next


The second line passes the value 10.1 to AddToTotal. Because the subroutine expects a variant parameter but 10.1 is a floating-point value, Visual Basic converts the argument into a variant containing a double and passes that to AddToTotal. Before it can add the parameter to TotalValue, Visual Basic must promote the values so they have the same data type. Because double precision variables can contain integer values but not vice versa, Visual Basic promotes TotalValue to a double. The program adds the two numbers and stores the result in TotalValue. The variable TotalValue is now a variant containing the double precision value 20.1.

The third line passes a string to AddToTotal. Visual Basic converts the string into a variant containing a string. AddToTotal then generates an error when it tries to add a string to a double precision value.

AddToTotal 10
AddToTotal 10.1
AddToTotal “Hello”

This is confusing, but other even stranger scenarios are possible. The following two lines set TotalValue equal to the string “10 days” with no error. When the code executes the first statement, it adds a variant containing the string “10” to the undefined variable TotalValue. The result is that TotalValue is a variant containing a string with value “10.”

Then the second passes a variant containing the string “days” to AddToTotal. The routine concatenates the string “days” to TotalValue and TotalValue becomes a variant containing the string “10 days.”

AddToTotal “10”
AddToTotal “ days”

The situation is confusing enough that some programmers may even try to execute the following statement. Here the programmer probably thinks the program will add 3 to TotalValue. The actual result depends on TotalValue’s current value. If it contains a string, the AddToTotal subroutine will concatenate the string “Three” to it. If TotalValue contains a numeric value, the program will generate an error when it tries to add a string value to a numeric value.

AddToTotal “Three”

All this confusion disappears if you declare the parameter passed to AddToTotal as an integer, double, string, or any other more specific data type. In every case, the proper behavior for the subroutine is much more obvious.

While variants have some big drawbacks, they do have a few advantages. First, they can have undefined values. For many database applications, it is useful to distinguish between no value and other values. For instance, in Visual Basic, integers are initialized to 0. It might be useful to distinguish between 0 and an uninitialized value. The following code shows how a routine can tell whether a variant has been initialized.

Private Sub MySub()
Static the_value As Variant
    If IsEmpty(the_value) Then
        ‘ Initialize the_value.
        the_value = 0
    End If
        :
End Sub

Variants can also contain arrays. Visual Basic’s Array statement allows you to quickly create a variant array containing specific data values. This makes it roughly the equivalent to a DATA statement in standard Basic and Fortran. The following code fills a variant array with employee names.

Dim employees As Variant

    employees = Array(“Amy”, “Brent”, “Julia”, “Michelle”, “Rod”)

The entries in a variant array are variants themselves and they can also be arrays. This is convenient for creating irregular array-like data structures. The following code creates the equivalent of a two-dimensional array in which each row in the array contains a different number of elements. The MsgBox statement prints the value of item 1 in row number 2. Variant arrays are numbered so the first entry has index 0, so this item has value 25. Figure 3.1 shows the irregular array graphically.

Private Sub Form_Load()
Dim row0 As Variant
Dim row1 As Variant
Dim row2 As Variant
Dim array_2d As Variant

    row0 = Array(1, 4, 5, 3, 8, 7, 9)
    row1 = Array(17, 12, 15)
    row2 = Array(22, 25, 21, 29, 27, 25)
    array_2d = Array(row0, row1, row2)

    MsgBox array_2d(2)(1)
End Sub

Another advantage of variants is that they can be declared publicly in classes and forms. Visual Basic does not allow forms or classes to declare public variables that are arrays. A program can work around this restriction by declaring a public variant variable that contains an array instead of declaring the array directly.


Figure 3.1  Variants allow a program to create the equivalent of an irregular two-dimensional array.

Finally, variants are used by Visual Basic to pass a variable number of arguments to a subroutine. The following function adds up the values of its parameters and returns the total.

Public Function AddItems(ParamArray values() As Variant)
Dim i As Long
Dim total As Double

    For i = LBound(values) To UBound(values)
        total = total + values(i)
    Next i
    AddItems = total
End Function

    :
Dim A As Integer
Dim B As Integer
Dim sub_total As Integer

    A = 101
    B = 2875
    :

    ‘ Add 13 to items A and B.
    sub_total = AddItems(13, A, B)

It is argued by some programmers that variants are the only data type a program should use. In fact, the World Wide Web scripting language VBScript, which is based on Visual Basic, only allows variant variables.

Despite their advantages, however, variants often add ambiguity to an otherwise simple situation. Use them only when you need their special features, like their ability to build irregular arrays or to implement public array members of a class.

Use Variant Subtype Functions

When you do use variants, use Visual Basic’s variant subtype functions to determine the kind of variable you are examining. The following code shows a more robust version of the AddItems function from the previous section. It uses the IsNumeric function to ensure that its arguments are numeric.

Const ERR_ARGUMENT_NOT_NUMERIC = vbObjectError + 17

Public Function AddItems(ParamArray values() As Variant)
Dim i As Long
Dim total As Double

    ‘ Make sure the parameters are numeric.
    For i = LBound(values) To UBound(values)
    If Not IsNumeric(values(i)) Then
        Err.Raise ERR_ARGUMENT_NOT_NUMERIC, _
            “MyProject.TotalItems”, _
            “Parameter” & Str$(i) & _
            “ with value ”“” & i & _
            “”“ is not numeric.”
    End If
    Next i

    ‘ Add the parameters.
    For i = LBound(values) To UBound(values)
        total = total + values(i)
    Next i
    AddItems = total
End Function


Previous Table of Contents Next


Products |  Contact Us |  About Us |  Privacy  |  Ad Info  |  Home

Use of this site is subject to certain Terms & Conditions, Copyright © 1996-1999 EarthWeb Inc.
All rights reserved. Reproduction whole or in part in any form or medium without express written permision of EarthWeb is prohibited.